package cn.globalph.housekeeper

import android.app.Application
import android.os.Build
import android.webkit.WebSettings
import cn.globalph.housekeeper.data.retrofit.HeaderInterceptor
import cn.globalph.housekeeper.utils.SystemUtils
import com.liulishuo.filedownloader.FileDownloader
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import java.io.File

class HouseKeeperApplication : Application(){
    companion object {
        lateinit var instance: Application
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        initData()
    }

    private fun initData(){
        FileDownloader.setupOnApplicationOnCreate(this)

        UMConfigure.init( this,  UMConfigure.DEVICE_TYPE_PHONE, null)
        if(BuildConfig.DEBUG) UMConfigure.setLogEnabled(true)

        HeaderInterceptor.VERSION_CODE = SystemUtils.getVersionCode(this)
        HeaderInterceptor.VERSION_NAME = SystemUtils.getVersionName(this)
        HeaderInterceptor.HTTP_HEADER = ("android" + " " + Build.MANUFACTURER
                + File.separator + Build.BRAND +
                File.separator + Build.MODEL + " " + Build.VERSION.RELEASE)
        HeaderInterceptor.PLATFORM = (Build.MANUFACTURER
                + File.separator + Build.BRAND +
                File.separator + Build.MODEL)
        HeaderInterceptor.PLATFORM_VERSION = Build.VERSION.RELEASE
        HeaderInterceptor.USER_AGENT = initUserAgent()
    }

    private fun initUserAgent():String{
        var userAgent: String? = ""
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            try {
                userAgent = WebSettings.getDefaultUserAgent(this)
            } catch (e: Exception) {
                userAgent = System.getProperty("http.agent")
            }

        } else {
            userAgent = System.getProperty("http.agent")
        }
        val sb = StringBuffer()
        var i = 0
        val length = userAgent!!.length
        while (i < length) {
            val c = userAgent[i]
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", c.toInt()))
            } else {
                sb.append(c)
            }
            i++
        }
        return sb.toString()
    }
}